package threading;

//通过懒汉模式实现一个单例模式
class SingletonLazy {
    //volatile 禁止指令重排序
    volatile private static SingletonLazy instance = null;

    public static SingletonLazy getInstance() {
        // 这个条件 , 判定是否要加锁 , 如果对象已经有了 , 就不必加锁了 , 此时本身就是安全的
        if (instance == null) {
            synchronized (SingletonLazy.class) {
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }

    private SingletonLazy() { }
}

public class ThreadDemo18 {
    public static void main(String[] args) {
        SingletonLazy s1 = SingletonLazy.getInstance();
        SingletonLazy s2 = SingletonLazy.getInstance();
        System.out.println(s1 == s2);
    }
}
